import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_order.dart';
import 'package:gold/http/apis.dart';
import 'package:gold/http/http.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_extension.dart';
import 'package:gold/utils/xfg_utils.dart';
import 'package:gold/widgets/common_widgets.dart';

/// @description:
/// @author tangzhentao
/// @created at 13:27 2024/12/14

class AppraiseViewmodel extends Viewmodel {
  /// 订单信息
  final int _orderId;
  /// 商品ID
  final int _productId;

  /// 标签
  final List<String> labels = ['整体评价', '性价比', '操作难易度', '包装与外观'];

  String _selectLabels = '';
  /// 选中标签
  String get selectLabels => _selectLabels;
  /// 用于请求的选中标签集合
  final List<String> _requestLabels = [];

  /// 添加图片数据
  final _addPhoto = AddPhoto(File(Res.imagesAppraisePhoto), isAdd: true);
  /// 标签
  List<AddPhoto> photos = [];

  /// 评价文字
  final TextEditingController controller = TextEditingController();
  final FocusNode focusNode = FocusNode();

  int _appraise = 0;
  /// 评价值
  int get appraise => _appraise;
  set appraise(int value) {
    hideKeyboard();
    if (_appraise != value) {
      _appraise = value;
      notifyListeners();
    }
  }

  int _isPrivate = 1;
  /// 是否匿名：0=不匿名，1=匿名
  int get isPrivate => _isPrivate;
  set isPrivate(int value) {
    hideKeyboard();
    if (_isPrivate != value) {
      _isPrivate = value;
      notifyListeners();
    }
  }

  AppraiseViewmodel(this._orderId, this._productId) {
    photos.add(_addPhoto);
  }

  /// 选中标签变化
  void changeSelectLabels(String label) {
    if (_requestLabels.contains(label)) {
      _requestLabels.remove(label);
    } else {
      _requestLabels.add(label);
    }
    _selectLabels = _requestLabels.join();
    notifyListeners();
  }

  /// 添加照片
  Future addPhoto() async {
    final needCount = 4 - (photos.length - 1);
    final files = await pickPhoto(max: needCount);
    if (files?.isNotEmpty == true) {
      if (needCount == files!.length) {
        photos.removeLast();
        photos.insertAll(0, files.map((file) => AddPhoto(file)).toList());
      } else {
        photos.removeLast();
        photos.insertAll(0, files.map((file) => AddPhoto(file)).toList());
        photos.add(_addPhoto);
      }
      setSuccessChange();
    }
  }

  /// 添加照片
  void deletePhoto(int index) {
    photos.removeAt(index);
    if (!photos.last.isAdd) {
      photos.add(_addPhoto);
    }
    setSuccessChange();
  }

  /// 发布
  Future publish() async {
    if (controller.text.isEmpty) {
      '请输入评价内容'.info();
      return;
    }
    String uploadResult = '';
    final List<String> images = [];
    if (photos.length > 1) {
      await Future.forEach(photos, (add) async {
        if (!add.isAdd) {
          if (add.http.isEmpty) {
            final data = await compressImage(await add.file.readAsBytes());
            final file = MultipartFile.fromBytes(data, filename: '${DateTime.now().millisecondsSinceEpoch}.png');
            final formData = FormData.fromMap({'file' : file});
            final result = await Http().uploadImage<String>(Apis.upload, formData, showErrorMsg: false);
            if (result.success && result.data?.isNotEmpty == true) {
              add.http = '${Apis.imageBaseUrl}${result.data!}';
              images.add(result.data!);
            } else {
              uploadResult = result.msg;
            }
          } else {
            images.add(add.http.replaceAll(Apis.imageBaseUrl, ''));
          }
        }
      });
    }
    if (uploadResult.isNotEmpty) {
      uploadResult.error();
      return;
    }
    final result = await Http().request<dynamic>(ApiOrder.review, data: {
      'order_id': _orderId, 'product_id': _productId,'rating': _appraise, 'comment': controller.text, 'is_private': _isPrivate, 'images': images.join(','),
    }, loadingText: '评价中...', successText: '已评价');
    if (result.success) {
      XfgNav.pop(true);
    }
  }

  @override
  void dispose() {
    controller.dispose();
    focusNode.dispose();
    super.dispose();
  }
}

class AddPhoto {
  final bool isAdd;
  final File file;
  String http;

  AddPhoto(this.file ,{this.http = '', this.isAdd = false});
}
